package com.yangyang.rpc.core.registry.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * Created by chenshunyang on 2016/11/28.
 */
public class ZookeeperManager {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperManager.class);

    private static CountDownLatch latch = new CountDownLatch(1);

    private static ZooKeeper zk;

    public static ZooKeeper getInstance(String address) {
        try {
            zk = new ZooKeeper(address, Constant.ZK_SESSION_TIMEOUT, new Watcher(){

                @Override
                public void process(WatchedEvent event) {
                    if (event.getState() == Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                    // session expire, close old and create new
                    if (event.getState() == Event.KeeperState.Expired) {
                        try {
                            zk.close();
                        } catch (InterruptedException e) {
                            LOGGER.error("", e);
                        }
                        zk = null;
                    }
                }

            });
            latch.await();
        } catch (Exception e) {
            LOGGER.error("",e);
        }
        return zk;
    }

    public static ZooKeeper getInstance() {
       return getInstance(Constant.ZK_ADSRESS);
    }
}
